<?php

namespace App\Jobs\Publish;

use App\Models\Common\TagData\Video\Vcattag;
use App\Models\Task\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class VcattagJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $ids;
    protected $option;
    public $tries   = 1;
    public $timeout = 30;
    public $taskid;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($option, $ids = '', $taskid = '')
    {
        $this->option = $option;
        $this->ids    = $ids;
        $this->taskid = $taskid;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        switch ($this->option) {
            // 将全部发布任务分成若干个小任务
            case 1:
                $total_num         = 0;
                $publish_chunk_num = config('custom.base.job.vcattag.publish_chunk_num');
                Vcattag::where('publish_status', 0)->select('id')->chunk($publish_chunk_num, function ($ids) use (&$total_num) {
                    if (!empty($ids)) {
                        $total_num += count($ids);
                        dispatch(new self(2, $ids, $this->taskid));
                    }
                });
                $total_num = ($total_num === 0) ? -1 : $total_num;
                self::updateTasks($this->taskid, ['total_num' => $total_num]);
                break;
            // 每次处理500条记录的发布小任务
            case 2:
                $publish_small_chunk_num = config('custom.base.job.vcattag.publish_small_chunk_num');
                foreach ($this->ids->chunk($publish_small_chunk_num) as $chunk_ids) {
                    $chunk_ids = $chunk_ids->pluck('id');
                    $vcattags    = Vcattag::whereIn('id', $chunk_ids)->get();
                    $datas     = [];
                    $data      = [];
                    foreach ($vcattags as $key => $value) {
                        // 服务商ID 目前服务商ID是瀚动的
                        $data['vcattag_id'] = $value->id;
                        // 分类编号
                        $data['vcattag_no'] = $value->vcattag_no;
                        // 名称
                        $data['name'] = $value->name;
                        // 标题
                        $data['title'] = $value->title;
                        // 副标题
                        $data['subtitle'] = $value->subtitle;
                        $datas[]          = $data;
                    }
                    DB::connection('interface')->beginTransaction();
                    try {
                        DB::connection('interface')->table('vcattags')->insert($datas);
                        DB::connection('interface')->commit();
                        self::updateVcattags($chunk_ids, ['publish_status' => 1]);
                        self::updateTasks($this->taskid, ['done_num' => DB::raw('done_num + ' . count($chunk_ids))]);
                    } catch (\Exception $e) {
                        DB::connection('interface')->rollback(); //事务回滚
                        dd($e->getMessage());
                    }
                }
                break;
            case 3:
                // 下线发布
                $total_num         = 0;
                $publish_chunk_num = config('custom.base.job.vcattag.publish_chunk_num');
                Vcattag::where('publish_status', 1)->select('id')->chunk($publish_chunk_num, function ($ids) use (&$total_num) {
                    if (!empty($ids)) {
                        $total_num += count($ids);
                        dispatch(new self(4, $ids, $this->taskid));
                    }
                });
                $total_num = ($total_num === 0) ? -1 : $total_num;
                self::updateTasks($this->taskid, ['total_num' => $total_num]);
                break;
            // 每次处理500条记录下线发布小任务
            case 4:
                $user_id = self::getTasks($this->taskid, 'user_id');
                self::deleteVcattags($this->ids->pluck('id'));
                self::updateVcattags($this->ids->pluck('id'), [
                    'publish_status' => 0,
                ]);
                self::updateTasks($this->taskid, ['done_num' => DB::raw('done_num +' . count($this->ids))]);
                break;
        }
    }

    /**
     * 更新分类表
     */
    public static function updateVcattags($ids, $data)
    {
        try {
            return Vcattag::whereIn('id', $ids)->update($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 删除接口库中分类表
     */
    public static function deleteVcattags($ids)
    {
        try {
            return DB::connection('interface')->table('vcattags')->whereIn('vcattag_id', $ids)->delete();
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 更新任务表
     */
    public static function updateTasks($id, $data)
    {
        try {
            return Task::where('id', $id)->update($data);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }

    /**
     * 获取tasks中的信息
     */
    public static function getTasks($id, $field)
    {
        try {
            return Task::where('id', $id)->value($field);
        } catch (\Exception $e) {
            dd($e->getMessage());
        }
    }
}
